var util = require('../../libs/util.js');
var moment = require('../../libs/moment.min.js');
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    pageSize: 10,
    pageNumber: 0,
    count: 0,
    page: 1,
    firstPage: true,
    prevPage: true,
    nextPage: true,
    lastPage: true,
    pay_date:moment().format('YYYY-MM-DD'),
    imgList:[],
    formType : 'add'
  },
  onShareAppMessage: function () {
    return {
      title: app.appName,
      path: '/pages/index/index'
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    wx.setNavigationBarTitle({ "title": "车辆档案" });
    var that = this;
    //更新数据
    that.setData({
      vehicle_id: e.id,
      tab: e.tab || 4,
      role_default:app.globalData.role_default,
      server:app.server
    });
    this.loadData();
  },
  bindInput: function (e) {
    var that = this;
    var item = String(e.currentTarget.id), item_value = {};
    item_value[item] = e.detail.value;
    this.setData(item_value);
    if(item == 'liter_number' || item == 'price_liter' ){
       if(isNaN(that.data.liter_number) == false && isNaN(that.data.price_liter) == false){
           that.setData({
            pay_price:Number(Number(that.data.liter_number)*Number(that.data.price_liter)).toFixed(1)
           })
       }
    }
    var distance = 0,add_100mile_oil=0,one_mile_price=0;
    if(that.data.prev_mile && that.data.mile){
      distance = (Number(that.data.mile) - Number(that.data.prev_mile))||0;
    }
    if(that.data.prev_mile && that.data.mile && that.data.liter_number){
      if(distance > 0 ){
        add_100mile_oil = (Number(that.data.liter_number)/distance*100).toFixed(1);
        one_mile_price = (Number(that.data.pay_price)/distance).toFixed(1);
      }
    }
    that.setData({
      distance:distance,
      add_100mile_oil:add_100mile_oil,
      one_mile_price:one_mile_price
    })
  },
  search: function () {
    this.loadData();
  },
  loadData: function () {
    var that = this;
    wx.showLoading({
      title: '请稍候...',
    });
    util.getData("/atapi/vehicle/vehicle/recharge", {
      'CO_ID': app.globalData.CO_ID,
      vehicle_id: that.data.vehicle_id,
      'searchVal': that.data.searchVal,
      'page': that.data.page,
      'pageSize': that.data.pageSize,
      'outsideUser': that.data.outsideUser
    }, function (res, error) {
      console.log(res); console.log(error)
      setTimeout(function(){
        wx.hideLoading();
      },100);
      if (res.data.success) {
        wx.setNavigationBarTitle({ "title": "车辆充电--" + res.data.data[0][0].plate });
        var count = res.data.data[3][0].COUNT;
        var pageNumber = Math.ceil(count / that.data.pageSize);
        that.setData({
          plate:res.data.data[0][0].plate,
          d_user_id:res.data.data[0][0].d_user_id,
          prev_mile:res.data.data[0][0].mile||0,
          total_mile:Number(res.data.data[1][0].total_mile||0).toFixed(0),
          total_price:Number(res.data.data[1][0].total_price||0).toFixed(0),
          total_100mile_oil:Number(res.data.data[1][0].total_100mile_oil||0).toFixed(1),
          user_id:app.globalData.user_id,
          is_fleet:app.globalData.role_default == 'fleet'?true:false,
          dataList: res.data.data[2],
          count: count,
          pageNumber: pageNumber,
          page: that.data.page == 0 ? 1 : that.data.page
        });
        that.setPageStatus();
      } else {
        that.setData({
          page: 0,
          dataList: []
        });
      }
    });
  },
  //翻页按钮状态
  setPageStatus: function () {
    var that = this;
    var page = that.data.page, pageNumber = that.data.pageNumber;
    if (pageNumber == 1) {
      that.setData({
        firstPage: true,
        prevPage: true,
        nextPage: true,
        lastPage: true
      });
    } else if (pageNumber > 1) {
      if (page == 1) {
        that.setData({
          firstPage: true,
          prevPage: true,
          nextPage: false,
          lastPage: false
        });
      } else if (page == pageNumber) {
        that.setData({
          firstPage: false,
          prevPage: false,
          nextPage: true,
          lastPage: true
        });
      } else if (page < pageNumber && page > 1) {
        that.setData({
          firstPage: false,
          prevPage: false,
          nextPage: false,
          lastPage: false
        });
      }
    }
  },
  //分页按钮操作
  pageChange: function (e) {
    var type = e.currentTarget.dataset.page;
    if (type == 'first') {
      this.setData({
        page: 1
      })
      this.loadData();
    }
    if (type == 'last') {
      this.setData({
        page: this.data.pageNumber
      })
      this.loadData();
    }
    if (type == 'prev') {
      this.setData({
        page: this.data.page - 1
      })
      this.loadData();
    }
    if (type == 'next') {
      this.setData({
        page: this.data.page + 1
      })
      this.loadData();
    }
  },
  showModal(e) {
    var that = this;
    this.setData({
      modalName: e.currentTarget.dataset.target,
      modalTitle: e.currentTarget.dataset.title,
      modalType:e.currentTarget.dataset.type
    })
    if(e.currentTarget.dataset.type == 'detail'){
       var id = e.currentTarget.id;
       var dataList = that.data.dataList;
       for(var i=0;i<dataList.length;i++){
         if(dataList[i].ID == id){
           var currentData = [];
           currentData.push({name:'充电度数',value:dataList[i].liter_number||0});
           currentData.push({name:'每度价格',value:dataList[i].price_liter||0});
           currentData.push({name:'电费',value:dataList[i].pay_price||0});
           currentData.push({name:'当前公里数',value:dataList[i].mile||0});
           currentData.push({name:'区间公里数',value:dataList[i].distance||0});
           currentData.push({name:'百公里耗电',value:dataList[i].add_100mile_oil||0});
           currentData.push({name:'每公里电价',value:dataList[i].one_mile_price||0});
           currentData.push({name:'充电人',value:dataList[i].oper_user});
           currentData.push({name:'充电日期',value:dataList[i].pay_date});
           currentData.push({name:'单据',value:dataList[i].picture?String(dataList[i].picture).split(','):[]});
            that.setData({
              _currentData:dataList[i],
               currentData:currentData
            })
         }
       }
    }
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  showPictrue: function (e) {
    var image = e.currentTarget.dataset.image;
    wx.previewImage({
      urls: image
    })
  },
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.dataset.url, // 当前显示图片的http链接
      urls: [e.currentTarget.dataset.url] // 需要预览的图片http链接列表
    })
  },
  chooseImage: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.name;
    var imgList = that.data.imgList;
    try{
      var formData = {
        'id': that.data.vehicle_id,
        'type':'recharge'
      };
    }catch(e){}
    wx.chooseImage({
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        console.log(res)
        wx.showLoading({
          title: '上传中...'
        });
        wx.uploadFile({
          url: app.server +'/atapi/vehicle/vehicle/uploadImage',
          header:{
            'Authorization': app.globalData.token
          },
            filePath: res.tempFilePaths[0],
            name: 'file',
            formData: formData,
            success: function (res) {
              var data = JSON.parse(res.data); console.log(data)
              if (data.success) {
                imgList.push(data.data);
                imgList = util.arrayDeleteEmpty(imgList);
                that.setData({
                  imgList: imgList
                });
              }else{
                wx.showToast({
                  title: "上传失败",
                  image: '/images/wrong.png',
                  duration: 2000
                });
              }
            },
            complete: function () {
              wx.hideLoading();
            }
          })
      }
    })
  },
  DelImg: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    console.log(index)
    var type = e.currentTarget.dataset.name;
    console.log(type)
    var imgList = that.data.imgList;
    var url = imgList[index];
    wx.showLoading({
      title: '删除中...'
    });
    if(url == ''){
      if (imgList.length == 1) {
        imgList = [];
      } else {
        imgList.splice(index, 1);
      }
      that.setData({
        imgList: imgList
      })
      wx.showToast({
        title: '删除成功',
        icon: 'success',
        duration: 2000,
        success: function () {

        }
      });
      return false;
    }
    util.putData("/atapi/vehicle/vehicle/deleteFile", {
      url: url
    }, function (res, error) {
      console.log(res); console.log(error)
      wx.hideLoading();
      if (error) {
        wx.showToast({ title: '删除失败', image: '/images/wrong.svg', duration: 2000 });
        return false;
      }
      if (res.data.success) {
        if (imgList.length == 1) {
          imgList = [];
        } else {
          imgList = util.arrayDeleteWithIndex(imgList, index,1);
        }
        that.setData({
          imgList: imgList
        })
        wx.showToast({
          title: '删除成功',
          icon: 'success',
          duration: 2000,
          success: function () {
            
          }
        });
      }
    });
  },
  //提交表单
  saveFormData: function () {
    var that = this;

    var formData = {};

    formData.liter_number = that.data.liter_number||'';
    formData.price_liter = that.data.price_liter||'';
    formData.pay_price = that.data.pay_price||'';
    formData.mile = that.data.mile||'';
    formData.picture = that.data.imgList.join(",");
    formData.pay_date = that.data.pay_date||'';
    console.log(formData)
    if (formData.liter_number == '') {
      wx.showToast({
        title: "请填写度数",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    if (isNaN(formData.liter_number) == true) {
      wx.showToast({
        title: "度数错误",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    if (formData.pay_price == '') {
      wx.showToast({
        title: "请填写电费",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    if (isNaN(formData.pay_price) == true) {
      wx.showToast({
        title: "电费错误",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    if (formData.price_liter == '') {
      wx.showToast({
        title: "请填写电价",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    if (isNaN(formData.price_liter) == true) {
      wx.showToast({
        title: "电价错误",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    if (formData.mile == '') {
      wx.showToast({
        title: "请填写公里数",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    if (isNaN(formData.mile) == true) {
      wx.showToast({
        title: "公里数错误",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    if (formData.picture == '') {
      wx.showToast({
        title: "请上传单据",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    formData.distance = that.data.distance
    formData.add_100mile_oil = that.data.add_100mile_oil;
    formData.one_mile_price = that.data.one_mile_price;
    formData.CO_ID = app.globalData.CO_ID;
    formData.ADD_USER = app.globalData.user_id;
    formData.oper_user = app.globalData.truename;
    formData.vehicle = that.data.vehicle_id;
    formData.distance = that.data.distance;
    formData.add_100mile_oil = that.data.add_100mile_oil;
    formData.one_mile_price = that.data.one_mile_price;
    //第一次填写加油记录
    if(Number(that.data.prev_mile) == 0){
      that.submitGasrecord(formData);
      return false;
    }
    if(Number(that.data.prev_mile) > 0 && Number(that.data.distance) <= 0){
      wx.showModal({
        title: '错误提示',
        content: "当前输入公里数小于或等于上次加油公里数，请输入真实公里数。",
        success (res) {
          if (res.confirm) {
            
          } 
        }
      })
      return false;
    }
    if(Number(that.data.prev_mile) > 0 && formData.distance < 100){
      wx.showModal({
        title: '温馨提示',
        content: "上次充电到现在行驶公里数小于100公里，确定填写当前公里数正确吗？",
        success (res) {
          if (res.confirm) {
            that.submitGasrecord(formData)
          } 
        }
      })
    }else{
      that.submitGasrecord(formData)
    }
    
  },
  submitGasrecord:function(formData){
    var that = this;
    wx.showLoading({
      title: '提交中...',
      mask: true
    })
    util.postData("/atapi/vehicle/vehicle/recharge", formData, function (res, error) {
      console.log(res); console.log(error)
      if (res.data.success) {
        wx.showToast({
          title: "提交成功",
          icon: "success",
          duration: 3000,
          success: function () {
            setTimeout(function () {
              that.hideModal();
              that.loadData();
            }, 3000);
          }
        });
      } else {
        wx.showToast({
          title: "提交失败",
          image: '/images/wrong.png',
          duration: 3000
        });
      }
      
    });
  },
  deleteData:function(){
    var that = this;
    var _currentData = that.data._currentData;
    wx.showModal({
      title: '温馨提示',
      content: '确定要删除吗？',
      success (res) {
        if (res.confirm) {
            util.deleteData("/atapi/vehicle/vehicle/recharge", {
              id: _currentData.ID,
              user_id:app.globalData.user_id,
              CO_ID:app.globalData.CO_ID,
              truename:app.globalData.truename,
              logs:that.data.plate+','+_currentData.name+','+_currentData.site+','+_currentData.fee+','+_currentData.upkeep_time+','+_currentData.maintenance_users
            }, function (res, error) {
              console.log(res); console.log(error)
              wx.hideLoading();
              if (error) {
                wx.showToast({ title: '删除失败', image: '/images/wrong.svg', duration: 2000 });
                return false;
              }
              if (res.data.success) {
                wx.showToast({
                  title: '删除成功',
                  icon: 'success',
                  duration: 2000,
                  success: function () {
                    setTimeout(function(){
                      that.hideModal();
                        that.loadData();
                    },3000)
                  }
                });
              }
            });
          }
        }
        })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})